package com.example.uavstatus;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class SettingsActivity extends AppCompatActivity {

    private EditText etServerIp, etControlPort, etDataPort;
    private Button btnSave;
    private SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        preferences = getSharedPreferences("uav_settings", MODE_PRIVATE);

        etServerIp = findViewById(R.id.et_server_ip);
        etControlPort = findViewById(R.id.et_control_port);
        etDataPort = findViewById(R.id.et_data_port);
        btnSave = findViewById(R.id.btn_save);

        // 加载当前设置
        loadSettings();

        btnSave.setOnClickListener(v -> saveSettings());
    }

    private void loadSettings() {
        etServerIp.setText(preferences.getString("server_ip", "192.168.1.11"));
        etControlPort.setText(String.valueOf(preferences.getInt("control_port", 4321)));
        etDataPort.setText(String.valueOf(preferences.getInt("data_port", 1234)));
    }

    private void saveSettings() {
        try {
            String serverIp = etServerIp.getText().toString().trim();
            int controlPort = Integer.parseInt(etControlPort.getText().toString());
            int dataPort = Integer.parseInt(etDataPort.getText().toString());

            if (serverIp.isEmpty()) {
                Toast.makeText(this, "服务器IP不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            if (controlPort <= 0 || controlPort > 65535 ||
                    dataPort <= 0 || dataPort > 65535) {
                Toast.makeText(this, "端口号必须在1-65535之间", Toast.LENGTH_SHORT).show();
                return;
            }

            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("server_ip", serverIp);
            editor.putInt("control_port", controlPort);
            editor.putInt("data_port", dataPort);
            editor.apply();

            Toast.makeText(this, "设置已保存", Toast.LENGTH_SHORT).show();
            finish();

        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的端口号", Toast.LENGTH_SHORT).show();
        }
    }
}